package de.yvert.jingle;

import java.util.Arrays;
import java.util.List;

public class ReaderWriterFactory
{

private static final String WRITER_PREFIX = "de.yvert.jingle.impl.writer.ImageWriter_";
private static final String READER_PREFIX = "de.yvert.jingle.impl.reader.ImageReader_";

private static final String[] READABLE_EXTENSIONS = new String[]
	{ "bmp", "ext", "jpg", "png", "tga", "ppm" };

private static final String[] WRITEABLE_EXTENSIONS = new String[]
	{ "exr", "hdr", "jpg" };

public static List<String> readableExtensions()
{ return Arrays.asList(READABLE_EXTENSIONS); }

public static List<String> writeableExtensions()
{ return Arrays.asList(WRITEABLE_EXTENSIONS); }

public static ImageWriter getWriter(ImageType type, String extension)
{
	try
	{
		Class<?> clazz = Class.forName(WRITER_PREFIX+extension);
		ImageWriter result = clazz.asSubclass(ImageWriter.class).newInstance();
		ImageType[] supportedTypes = result.supportedTypes();
		boolean ok = false;
		for (ImageType t : supportedTypes)
			if (t == type) ok = true;
		if (!ok) throw new RuntimeException("No writer found!");
		return result;
	}
	catch (ClassNotFoundException e)
	{ throw new RuntimeException(e); }
	catch (InstantiationException e)
	{ throw new RuntimeException(e); }
	catch (IllegalAccessException e)
	{ throw new RuntimeException(e); }
}

public static ImageWriter getWriter(ImageType type)
{
	String extension = type.getDefaultExtension();
	if (extension == null) throw new RuntimeException("No default extension for this image type!");
	return getWriter(type, extension);
}

public static ImageReader getReader(String extension)
{
	try
	{
		Class<?> clazz = Class.forName(READER_PREFIX+extension);
		return clazz.asSubclass(ImageReader.class).newInstance();
	}
	catch (ClassNotFoundException e)
	{ throw new RuntimeException(e); }
	catch (InstantiationException e)
	{ throw new RuntimeException(e); }
	catch (IllegalAccessException e)
	{ throw new RuntimeException(e); }
}

}
